import { defineStore } from "pinia"

import router from "@/router/index"
// import api from "@/api"
//引入本地完整路由配置
import allRoutes from "@/router/allRoutes"
//引入递归匹配路由的方法
import recursion from "@/utils/recursionRoute"

const useMenus = defineStore("menus", () => {
    let menus = ref([]);
    //用户的路由数据,后续可以通过这个创建出菜单数据
    let userRoutes = ref([])
    //展开和收起菜单
    let menuCollapse = ref(false)
    //封装一个发起请求的aciton
    let getMenus = async (params = { type: 1 ,order_by:1}) => {
        try {
            let res = await api.getRoleMenusApi(params);
            // console.log(res)
            menus.value = res.data;
            setUserRoute(res.data)
            return Promise.resolve(res)
        } catch (e) {
            return Promise.reject(e.toString())
        }
    }
    //封装一个方法,通过获取的角色菜单,和本地的完整路由进行递归匹配,获取用户路由数据
    let setUserRoute = (menulist) => {
        // console.log('----menulist',menulist)
        let result = recursion(allRoutes, menulist)
        // console.log('---userRoutes', userRoutes)
        // 通过路由的addRoute方法将路由动态的添加到项目中
        // let router = useRouter();
    
        console.log(router)
        //addRoute是一个动态添加路由的方法,里面的参数是 {path:'xx',component:xxx}
        result.forEach(route => {
            // console.log(route)
            // router.addRoute(route)
            // console.log(router.addRoute())
            router.addRoute('home',route)
        })
        console.log(router.getRoutes())
        userRoutes.value = result;
    }
    return {
        menus,
        getMenus,
        userRoutes,
        menuCollapse
    }
})

export default useMenus